import React, { useState, useEffect, useRef } from 'react';
import { Select, Input, theme, Space, Tag, Row, Col, message, Modal, Table, Avatar, Tooltip, Popover, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import { Link } from '@umijs/max';
import dayjs from 'dayjs';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import useCurrentUser from '@/utils/useCurrentUser';
import ProjectDetail from "@/components/Projects/projectDetail";
import QRCodeStyling from "qr-code-styling";
import { WarningFilled, QrcodeOutlined, SendOutlined } from '@ant-design/icons';


const qrCode = new QRCodeStyling({
    width: 128,
    height: 128,
    dotsOptions: {
        color: "#4267b2",
        type: "rounded"
    },
    imageOptions: {
        crossOrigin: "anonymous",
        margin: 20
    }
});
// 列配置
const statusConf = {
    0: {
        text: '未开始',
        color: 'rgba(153, 153, 153,0.5)',
    },
    1: {
        text: '进行中',
        color: 'green',
    },
    2: {
        text: '已完成',
        color: '#3587C9',
    },
    3: {
        text: '已延期',
        color: '#ff4800',
    },
};

const ProjectTable = ({ item }) => {
    const { token } = theme.useToken();
    const { currentUser } = useCurrentUser();

    const columns = [
        {
            title: '项目名称',
            dataIndex: 'projectName',
            key: 'projectName',
            render: (text, record) => {
                return <a style={{ color: token?.colorPrimary }} onClick={() => viewTrend(record)}>
                    <b>{text}</b>
                </a>;
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            valueType: 'select',
            options: [
                { label: '未开始', value: 0 },
                { label: '进行中', value: 1 },
                { label: '已完成', value: 2 },
                { label: '已延期', value: 3 }
            ],
            render: (text, { status }) => {
                const color = status === 2 ? 'green' : 'volcano';
                return (
                    <Tag color={statusConf[status].color} key={status}>
                        {text}
                    </Tag>
                );
            },
        },
        {
            title: '消耗积木',
            dataIndex: 'block',
            key: 'block',
            sorter: (a, b) => a.block - b.block,
            search: false,
            hideInTable: currentUser?.isCompany === 1,
        },
        {
            title: '项目积分',
            dataIndex: 'points',
            key: 'points',
            sorter: (a, b) => a.points - b.points,
            search: false
        },
        {
            title: '参与人员',
            dataIndex: 'userNames',
            key: 'userNames',
            search: false,
            width: 360,
            render: (text, record) => (record.userNames?.split('/')?.map(it => (<Tag key={it}>{it}</Tag>)))
        },
        {
            title: '节点完成度',
            dataIndex: 'projectNode',
            key: 'projectNode',
            search: false,
            render: (text, { finishItemCount, allItemCount, ...other }) => (
                <Space>
                    {finishItemCount}/{allItemCount} <a onClick={async () => {
                        let res = await getFetch({ url: "/user" });
                        const users = res?.data?.dataList ?? [];
                        Modal.info({
                            title: '节点详情',
                            width: "80%",
                            icon: () => false,
                            closable: true,
                            footer: false,
                            maskClosable: true,
                            content: (
                                <Table
                                    size='small'
                                    dataSource={other.itemList}
                                    columns={[
                                        {
                                            title: '节点名称',
                                            dataIndex: 'missionName',
                                            key: 'missionName',
                                        }, {
                                            title: '节点状态',
                                            dataIndex: 'status',
                                            key: 'status',
                                            render: (text, { status }) => {
                                                return (
                                                    <Tag color={statusConf[status].color} key={status}>
                                                        {statusConf[status].text}
                                                    </Tag>
                                                );
                                            }
                                        }, {
                                            title: '节点积分',
                                            dataIndex: 'itemPoints',
                                            key: 'itemPoints',
                                        }, {
                                            title: '计划截止时间',
                                            dataIndex: 'planEnd',
                                            key: 'planEnd',
                                            render: (text, record) => {
                                                return (
                                                    <Tooltip title={record?.planEnd}>
                                                        <span style={{ color: record?.planEnd && dayjs(record?.planEnd).valueOf() < dayjs().valueOf() ? "red" : "" }}>
                                                            {record?.planEnd ? record?.planEnd : "-"}
                                                        </span>
                                                    </Tooltip>
                                                );
                                            }
                                        },
                                        {
                                            title: '当前执行人',
                                            dataIndex: 'user',
                                            key: 'user',
                                            render: (text, record) => {
                                                const cur = users.find(user => user.id === record.userId);
                                                return (
                                                    <div className="centerl gap6">
                                                        <Avatar src={cur?.headUrl}>{cur?.name?.charAt(0)}</Avatar>
                                                        <span>  {cur?.name}</span>
                                                    </div>
                                                );
                                            }
                                        },
                                        {
                                            title: '进度提醒',
                                            valueType: 'option',
                                            width: 140,
                                            render: (text, record) => (
                                                <Popconfirm
                                                    title={"发送提醒"}
                                                    description={
                                                        <div style={{ paddingBottom: 12 }}>
                                                            <Input.TextArea rows={3} showCount id={"content" + record.id} defaultValue={"请尽快完成该节点任务"}></Input.TextArea>
                                                        </div>
                                                    }
                                                    cancelText="取消"
                                                    okText="确认"
                                                    onConfirm={async () => {
                                                        const curreply = document.getElementById('content' + record.id).value;
                                                        let res = await doFetch({
                                                            url: "/itemMsg", params: {
                                                                "itemId": record.id,
                                                                "reply": curreply,
                                                                "bereplyUserId": record.userId
                                                            }
                                                        })
                                                        if (res.code === 0) {
                                                            message.success("消息已发送");
                                                            document.getElementById('content' + record.id).value = "请尽快完成该节点任务"
                                                        }
                                                    }}
                                                    onCancel={() => {
                                                        document.getElementById('content' + record.id).value = "请尽快完成该节点任务"
                                                    }}
                                                    placement="bottom"
                                                    arrows={false}
                                                >
                                                    <a><SendOutlined /> 发送</a>
                                                </Popconfirm>

                                            )
                                        }
                                    ]}

                                />
                            ),
                        })
                    }} style={{ color: token?.colorPrimary }}>查看</a>
                </Space>
            ),
        },
        {
            title: '项目结束日期',
            dataIndex: 'deadline',
            key: 'deadline',
            search: false,
        },
        {
            title: '二维码',
            valueType: 'option',
            width: 88,
            render: (text, record) => (
                <Space size="middle" className='noinner'>
                    <Popover arrow={false} destroyTooltipOnHide={false} content={<div className='center columns'>
                        <div id={record.id + "s"} style={{ width: 128, height: 128 }} />
                        <small style={{ textAlign: "center", opacity: 0.5 }}>右键复制二维码图片 <Link target="_blank" rel="noopener noreferrer" style={{color: token?.colorPrimary }} to={"/project/"+record.id}>查看</Link></small>
                    </div>} placement="bottomLeft" onOpenChange={(open) => {
                        if (open) {
                            setTimeout(() => {
                                const qrdom = document.getElementById(record.id + "s");
                                qrCode.append(qrdom);
                                qrCode.update({
                                    data: `${location.origin + location.pathname}#/project/${record.id}`,
                                });
                            }, 300);
                        }
                    }}>
                        <div className="sorts" style={{ cursor: "pointer" }}>
                            <QrcodeOutlined style={{ fontSize: 18, color: token?.colorPrimary }} />
                        </div>
                    </Popover>
                </Space>
            ),
        },
    ];


    function viewTrend(record) {
        setModal((s) => ({
            ...s,
            open: true,
            title: <span>查看项目: <b> {record?.projectName} </b> 的详情</span>,
            item: record
        }));
    }

    const [modal, setModal] = useState({
        open: false,
        footer: false,
        onCancel: () => {
            setModal((s) => ({
                ...s,
                open: false,
            }));
        },
    });



    return (
        <div style={{ marginBottom: 12 }}>

            <Modal
                {...modal}
                width={"90%"}
                style={{ top: 12 }}
                destroyOnClose
            >
                <ProjectDetail curid={modal?.item?.id}></ProjectDetail>
            </Modal>

            <AutoTable
                headerTitle="项目列表"
                columns={columns}
                path={'/project/getProjectPage'}
                extraparams={{ orgId: currentUser.orgId }}

                method='post'
            />
        </div>
    );
};

export default ProjectTable;
